package net.sf.jimex.project;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * andrew 27.02.2006 23:14:32
 */
public class Worklog {
    private String issueKey;
    private int spentTime;
    private String message;
    private static final Pattern PATTERN_WORKLOG = Pattern.compile("([A-Z]*-\\d*)\\s*\\/\\s*(?:(?:(\\d)*\\s*d\\s*)?(?:(\\d*)\\s*h\\s*)*?(?:(\\d*)\\s*m\\s*)?)\\s*:([\\w|\\W]*)");

    public Worklog(String issueKey, int spentTime, String message) {
        this.issueKey = issueKey;
        this.spentTime = spentTime;
        this.message = message;
    }

    public String getIssueKey() {
        return issueKey;
    }

    public int getSpentTime() {
        return spentTime;
    }

    public String getMessage() {
        return message;
    }

    public static Worklog makeWorklog(String worklogString) {
        Matcher matcher = PATTERN_WORKLOG.matcher(worklogString);
        if (!matcher.find())
            throw new IllegalArgumentException("wrong worklog string");
        String issueKey = matcher.group(1);
        int days = convertToInt(matcher.group(2));
        int hours = convertToInt(matcher.group(3));
        int minutes = convertToInt(matcher.group(4));
        int result = minutes + (hours + days*24)*60;
        String message = matcher.group(5);
        Worklog worklog = new Worklog(issueKey, result, message);
        return worklog;
    }

    public static int convertToInt(String s) {
        if (s == null)
            return 0;
        s = s.trim();
        return Integer.parseInt(s);
    }
}
